package com.spzx.channel.service.impl;

import com.alibaba.fastjson2.JSON;
import com.spzx.channel.configure.ThreadPoolConfig;
import com.spzx.channel.domain.ItemVo;
import com.spzx.channel.service.IItemService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuStockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class ItemServiceImpl implements IItemService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public ItemVo item(Long skuId) throws Exception {

        //远程调用商品微服务接口之前 提前知道用户访问商品SKUID是否存在于bitmap中
        String key = "sku:product:data";
        Boolean flag = redisTemplate.opsForValue().getBit(key, skuId);
        if (!flag) {
            log.error("用户查询商品sku不存在：{}", skuId);
            //查询数据不存在直接返回空对象
            throw new ServiceException("用户查询商品sku不存在");
        }

        ItemVo itemVo = new ItemVo();

        //任务1.获取sku信息
        //异步编排: CompletableFuture:
            //1.supplyAsync() 异步执行有返回值的任务
            //2.thenAcceptAsync() 连接两个有依赖关系的异步任务（前一个的输出作为后一个的输入）
            //3.runAsync() 只负责运行

        CompletableFuture<ProductSku> skuCompletableFuture = CompletableFuture.supplyAsync(() -> {
            R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (R.FAIL == productSkuResult.getCode()) {
                throw new ServiceException(productSkuResult.getMsg());
            }
            ProductSku productSku = productSkuResult.getData();
            if (productSku == null) {
                throw new ServiceException("商品不存在");
            }
            itemVo.setProductSku(productSku);
            return productSku;
        }, threadPoolExecutor);


        //任务2.获取商品信息
        //由于下面需要编排的代码用到了上面代码所执行得到的结果,所以需要串行,使用thenAcceptAsync() 并且用传给他的编排来调用
        CompletableFuture<Void> voidCompletableFuture = skuCompletableFuture.thenAcceptAsync((productSku) -> {
            R<Product> productResult = remoteProductService.getProduct(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productResult.getCode()) {
                throw new ServiceException(productResult.getMsg());
            }
            Product product = productResult.getData();
            itemVo.setProduct(product);
            itemVo.setSliderUrlList(Arrays.asList(product.getSliderUrls().split(",")));
            itemVo.setSpecValueList(JSON.parseArray(product.getSpecValue()));
        }, threadPoolExecutor);


        //任务3.获取商品最新价格
        //由于这段代码既不需要参数,也不需要返回值,所以并行编排,用runAsync()实现
        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            R<SkuPrice> skuPriceResult = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuPriceResult.getCode()) {
                throw new ServiceException(skuPriceResult.getMsg());
            }
            SkuPrice skuPrice = skuPriceResult.getData();
            itemVo.setSkuPrice(skuPrice);
        }, threadPoolExecutor);


        //任务4.获取商品详情
        CompletableFuture<Void> voidCompletableFuture2 = skuCompletableFuture.thenAcceptAsync((productSku) -> {
            R<ProductDetails> productDetailsResult = remoteProductService.getProductDetails(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productDetailsResult.getCode()) {
                throw new ServiceException(productDetailsResult.getMsg());
            }
            ProductDetails productDetails = productDetailsResult.getData();
            itemVo.setDetailsImageUrlList(Arrays.asList(productDetails.getImageUrls().split(",")));
        }, threadPoolExecutor);


        //任务5.获取商品规格对应商品skuId信息
        CompletableFuture<Void> voidCompletableFuture3 = skuCompletableFuture.thenAcceptAsync((productSku) -> {
            R<Map<String, Long>> skuSpecValueResult = remoteProductService.getSkuSpecValue(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == skuSpecValueResult.getCode()) {
                throw new ServiceException(skuSpecValueResult.getMsg());
            }
            Map<String, Long> skuSpecValueMap = skuSpecValueResult.getData();
            itemVo.setSkuSpecValueMap(skuSpecValueMap);
        }, threadPoolExecutor);


        //任务6.获取商品库存信息
        //由于最后也用到了productSku,所以也串行调用
        CompletableFuture<Void> voidCompletableFuture4 = skuCompletableFuture.thenAcceptAsync((productSku) -> {
            R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuStockResult.getCode()) {
                throw new ServiceException(skuStockResult.getMsg());
            }
            SkuStockVo skuStockVo = skuStockResult.getData();
            itemVo.setSkuStockVo(skuStockVo);
            productSku.setStockNum(skuStockVo.getAvailableNum());
        }, threadPoolExecutor);

        //进行异步编排
        CompletableFuture.allOf(
                skuCompletableFuture,
                voidCompletableFuture,
                voidCompletableFuture1,
                voidCompletableFuture2,
                voidCompletableFuture3,
                voidCompletableFuture4
        ).join();

        return itemVo;
    }
}